package com.lichongbing.lyoggl.Interceptor;

import com.lichongbing.lyoggl.annotation.AccessLimit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;

/**
 * @author lichongbing
 * @version 1.0.0
 * @createdate 2021/12/26 2:09 下午
 * @description: TODO
 */
@Component
@RestController
@RequestMapping("/timeline")
public class FangshuaInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private RedisTemplate redisTemplate;

    public String keys = " ";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断请求是否属于方法的请求
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod=(HandlerMethod) handler;

            //获取方法中的注解，看是否有该注解
            AccessLimit accessLimit = handlerMethod.getMethodAnnotation(AccessLimit.class);
            if(accessLimit==null){
                return true;
            }
            int seconds = accessLimit.seconds();

            int maxcount = accessLimit.maxcount();
            boolean login = accessLimit.needLogin();
            String key = request.getRequestURI();
            keys= key;
            //如果需要登录
            if(login){
                //获取登录的session进行判断
                //.......
                key+=""+"1"; //用户id userId
            }

            //从redis中获取用户访问的次数
            //AccessKey ak = AccessKey.withExpire(seconds);
            Integer count= (Integer)redisTemplate.opsForValue().get(key);
            if(count==null){
                //第一次访问
                redisTemplate.opsForValue().set(key,1);
            }else if(count<maxcount){
                //加1
                redisTemplate.opsForValue().set(key,(Integer)redisTemplate.opsForValue().get(key)+1);
            }else{
                //超出访问次数
                render(response,key+"接口请求次数过多！");
                return false;
            }
        }
        return true;
    }

    private void render(HttpServletResponse response, String message)throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        OutputStream out = response.getOutputStream();
        out.write(message.getBytes("UTF-8"));
        out.flush();
        out.close();
    }
    @PostMapping("delay")
    @Scheduled(fixedDelay = (long) (1 * 1 * 1000))    // 每隔10分钟执行一次
    @Scheduled(cron = "0 0 2 * * ?")
    public void delay(){
        redisTemplate.delete(keys);
    }


}
